package com.mzj.saas.mservice.smartlock.service.youdian;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.enums.LockAlarmTypeEnum;
import com.mzj.saas.mservice.lock.entity.LockAlarm;
import com.mzj.saas.mservice.lock.entity.LockOpenLog;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lock.service.LockAlarmService;
import com.mzj.saas.mservice.lock.service.LockOpenLogService;
import com.mzj.saas.mservice.smartlock.service.ruanku.SmartLockService;
import com.mzj.saas.mservice.smartlock.vo.youdian.ydCallBackVo;
import com.mzj.saas.mservice.smartlock.vo.youdian.ydDataVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 优电-事件回调处理
 * 20230615
 * xiaolong
 */
@Service
public class SmartLockYdEventHandleService {


    private static final Logger log = LoggerFactory.getLogger(SmartLockYdEventHandleService.class);

    private static final String authSql = "SELECT a.id,a.user_name as userName  FROM saas_smart_lock_auth a "
            + "LEFT  JOIN  saas_smart_lock_pwd p ON a.id = p.lock_auth_id \n"
            + "WHERE p.return_pwd_id = ?";

    private static final String cardSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_card c ON a.id = c.lock_auth_id WHERE c.return_card_id  = ?";

    private static final String faceSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_face f ON a.id = f.lock_auth_id WHERE  f.return_face_id = ?";

    @Autowired
    private SmartLockYdService smartLockYdService;
    @Autowired
    private SmartLockService smartLockService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private LockOpenLogService lockOpenLogService;
    @Autowired
    private LockAlarmService lockAlarmService;

    /**
     * 注册智能锁
     *
     * @param sn 智能锁SN号
     * @return
     */
    public ResultBean<String> insertSmartLock(String sn) {
        String stringResultBean = smartLockYdService.insertSmartLock(sn);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        if (code != 0) {
            String message = (String) JSONObject.parseObject(stringResultBean).get("message");
            return ResultBean.failedResultOfParamWithMsg(message);
        }
        return ResultBean.successfulResult(sn);
    }

    /**
     * 开锁日志
     *
     * @param vo
     */
    public String logEventHandle(ydCallBackVo vo) {
        ydDataVo pushContent = vo.getPushContent();
        SmartLock smartLock = smartLockService.findBySn(vo.getImei());
        if (smartLock == null) {
            log.warn("优电-开锁日志, 数据库未找到设备信息, deviceId={}", vo.getPushContent());
            //智能锁没有绑在房子上不用记录，直接返回
            return "ok";
        }
        // 开门记录
        LockOpenLog openLog = new LockOpenLog();
        switch (pushContent.getPasswordType()) {
            case 2://临时密码
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(0);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(vo.getCreateTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth1 = jdbcTemplate.queryForObject(authSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), pushContent.getPasswordId());
                openLog.setUserId(smartLockAuth1.getId());
                openLog.setOpenUserName(smartLockAuth1.getUserName());//开门人姓名
                lockOpenLogService.save(openLog);
                return "ok";
            case 3://门卡开锁
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(11);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(vo.getCreateTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth2 = jdbcTemplate.queryForObject(cardSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), pushContent.getPasswordId());
                openLog.setUserId(smartLockAuth2.getId());
                openLog.setOpenUserName(smartLockAuth2.getUserName());//开门人姓名
                lockOpenLogService.save(openLog);
                return "ok";
            case 11://人脸开锁
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(32);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(vo.getCreateTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth3 = jdbcTemplate.queryForObject(faceSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), pushContent.getPasswordId());
                openLog.setUserId(smartLockAuth3.getId());
                openLog.setOpenUserName(smartLockAuth3.getUserName());//开门人姓名
                lockOpenLogService.save(openLog);
                return "ok";
            default:
                return "ok";
        }
    }


    /**
     * 心跳日志
     *
     * @param vo
     */
    public String lockOnlineCallBack(ydCallBackVo vo) {
        ydDataVo pushContent = vo.getPushContent();
        SmartLock smartLock = smartLockService.findBySn(vo.getImei());
        if (smartLock == null) {
            log.warn("优电-心跳日志, 数据库未找到设备信息, deviceId={}", vo.getPushContent());
            //智能锁没有绑在房子上不用记录，直接返回
            return "ok";
        }
        Integer signalStrength = pushContent.getSignalLevel();
        if (signalStrength >= 4) {
            smartLock.setSignalLevel(1);
        } else if (signalStrength >= 3 && signalStrength < 4) {
            smartLock.setSignalLevel(2);
        } else {
            smartLock.setSignalLevel(3);
        }
        smartLock.setElectricQuantity(pushContent.getBatteryLevel());
        smartLockService.save(smartLock);
        return "ok";
    }


    /**
     * 告警日志
     *
     * @param vo
     */
    public String lockAlarm(ydCallBackVo vo) {
        ydDataVo pushContent = vo.getPushContent();
        SmartLock smartLock = smartLockService.findBySn(vo.getImei());
        if (smartLock == null) {
            log.warn("优电-告警日志, 数据库未找到设备信息, deviceId={}", vo.getPushContent());
            //智能锁没有绑在房子上不用记录，直接返回
            return "ok";
        }
        LockAlarm lockAlarm = new LockAlarm();
        switch (pushContent.getAlarmType()) {
            case 1://防拆报警(防撬告警)
                lockAlarm.setAlarmType(LockAlarmTypeEnum.PICK_PROOF.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(pushContent.getBatteryLevel());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmService.save(lockAlarm);
                return "ok";
            case 3:// 低电量
                lockAlarm.setAlarmType(LockAlarmTypeEnum.LOW.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(pushContent.getBatteryLevel());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmService.save(lockAlarm);
                return "ok";
            default:
                return "ok";
        }
    }
}
